//
//  RoomList.m
//  Maze
//
//  Created by Lin Tian on 9/13/11.
//  Copyright 2011 tina. All rights reserved.
//

#import "RoomList.h"
#import "CreateRoomLayer.h"
#import "SlidingMenuGrid.h"
#import "RoomListBackgroundLayer.h"
#import "OptionLayer.h"
#import "SimpleAudioEngine.h"

#define CREATROOM 1
#define JOINROOM 2
#define LOGOUT 3
#define OPTION 4

#define MENUGRID 512
#define BACKGROUND -2

#define OPTIONLAYER 100
#define CREATELAYER 101

@implementation RoomList

@synthesize tempLabel;
@synthesize roomPool = _roomPool;
@synthesize menuGrid;
@synthesize previousCount;

//need a function to update menugrid


-(void)updateRoomList:(ccTime)dt{
    
    id target = self;
    
    int count = [_roomPool count];
    if(count == previousCount){
        return;
    }
    
    NSMutableArray* allItems = [NSMutableArray arrayWithCapacity:100];
    for (int i = 0; i < count; i++)
    {
        CCSprite* normalSprite = [CCSprite spriteWithFile:@"RoomItem.png"];
        CCSprite* selectedSprite = [CCSprite spriteWithFile:@"RoomItem.png"];
        Room *room = [self.roomPool objectAtIndex:i];
        NSString *idstring = [NSString stringWithFormat:@"%d", room.roomId];
        CCLabelTTF *idlabel = [CCLabelTTF labelWithString:idstring 
                                                 fontName:@"Marker Felt" 
                                                 fontSize:40];
        
        CCMenuItemSprite* item =[CCMenuItemSprite itemFromNormalSprite:normalSprite 
                                                        selectedSprite:selectedSprite 
                                                                target:target 
                                                              selector:@selector(LaunchLevel:)];
        idlabel.position = ccp(item.contentSize.width*0.7, item.contentSize.height*0.85);
        
        NSString *builder = [NSString stringWithFormat:@"%d", room.owner.playerId];
        CCLabelTTF *builderlabel = [CCLabelTTF labelWithString:builder
                                                      fontName:@"Marker Felt" 
                                                      fontSize:40];
        builderlabel.position = ccp(item.contentSize.width*0.7, item.contentSize.height*0.5);
        
        NSString *num = [NSString stringWithFormat:@"%d/%d",room.currentNumPlayers, room.capacity];
        CCLabelTTF *numlabel = [CCLabelTTF labelWithString:num
                                                  fontName:@"Marker Felt" 
                                                  fontSize:40];
        numlabel.position = ccp(item.contentSize.width * 0.7, item.contentSize.height*0.2);
        [item addChild:idlabel z:2];
        [item addChild:builderlabel z:2];
        [item addChild:numlabel z:2];
        [allItems addObject:item];
      
    }
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    self.menuGrid = [SlidingMenuGrid menuWithArray:allItems cols:2 rows:2 position:CGPointMake(winSize.width * 0.2, winSize.height*0.8) padding:CGPointMake(winSize.width/2, winSize.height * 0.4) verticalPaging:NO];
    previousCount = count;
    [self addChild:self.menuGrid z:-1 tag:MENUGRID]; 
    return;
}

+(CCScene*) sceneWithRoomList:(NSMutableArray*)roomList
{
	CCScene *myScene = [CCScene node];
	
	RoomList *roomListLayer = [[RoomList alloc] initWithRoomList:roomList];
	
	[myScene addChild:roomListLayer z:0 tag:ROOMLISTPAGE];
   
    RoomListBackgroundLayer *bg = [RoomListBackgroundLayer node];
    [myScene addChild:bg z:BACKGROUND];
	
	return myScene;
}


-(id)initWithRoomList:(NSMutableArray*)roomList
{
	if ((self = [super init])) {
        [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"TileMap.caf"];
        /********************  setup the menu  *********************/
        [self setupMenu];
        
        /*******************  initial roomList  ********************/
        self.roomPool =[NSMutableArray array];
               //code here is for debug use. delete it when real login page is on
        tempLabel = [CCLabelTTF labelWithString:@"This is the RoomList Page. It shows all the rooms currently avaliable in server. Press anybutton go to roomInfo screen" 
                                     dimensions:CGSizeMake(400, 150) 
                                      alignment:UITextAlignmentCenter
                                       fontName:@"Verdana-Bold"
                                       fontSize:25];
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        tempLabel.position = ccp(winSize.width - tempLabel.contentSize.width, winSize.height - tempLabel.contentSize.height);
        //[self addChild:tempLabel];
        
        //set slidingMenue
        CCNode *old = [self getChildByTag:MENUGRID];
        if(old != nil){
            [self removeChild:old cleanup:YES];
        }
        
        id target = self;
        
        self.previousCount = [roomList count];
        
        NSMutableArray* allItems = [NSMutableArray arrayWithCapacity:100];
        for (int i = 0; i < previousCount; i++)
        {
            CCSprite* normalSprite = [CCSprite spriteWithFile:@"RoomItem.png"];
            CCSprite* selectedSprite = [CCSprite spriteWithFile:@"RoomItem.png"];
            Room *room = [roomList objectAtIndex:i];
            NSString *idstring = [NSString stringWithFormat:@"%d", room.roomId];
            CCLabelTTF *idlabel = [CCLabelTTF labelWithString:idstring 
                                                     fontName:@"Marker Felt" 
                                                     fontSize:40];
            
            CCMenuItemSprite* item =[CCMenuItemSprite itemFromNormalSprite:normalSprite 
                                                            selectedSprite:selectedSprite 
                                                                    target:target 
                                                                  selector:@selector(LaunchLevel:)];
            idlabel.position = ccp(item.contentSize.width*0.7, item.contentSize.height*0.85);
            
            NSString *builder = [NSString stringWithFormat:@"%d", room.owner.playerId];
            CCLabelTTF *builderlabel = [CCLabelTTF labelWithString:builder
                                                          fontName:@"Marker Felt" 
                                                          fontSize:40];
            builderlabel.position = ccp(item.contentSize.width*0.7, item.contentSize.height*0.5);
            
            NSString *num = [NSString stringWithFormat:@"%d/%d",room.currentNumPlayers, room.capacity];
            CCLabelTTF *numlabel = [CCLabelTTF labelWithString:num
                                                      fontName:@"Marker Felt" 
                                                      fontSize:40];
            numlabel.position = ccp(item.contentSize.width * 0.7, item.contentSize.height*0.2);
            [item addChild:idlabel z:2];
            [item addChild:builderlabel z:2];
            [item addChild:numlabel z:2];
            [allItems addObject:item];
        }
      
        self.menuGrid = [SlidingMenuGrid menuWithArray:allItems cols:2 rows:2 position:CGPointMake(winSize.width * 0.2, winSize.height*0.8) padding:CGPointMake(winSize.width/2, winSize.height * 0.4) verticalPaging:NO];
        [self addChild:self.menuGrid z:-1 tag:MENUGRID]; 
        
        //schedule
        [self schedule:@selector(updateRoomList:) interval:1]; 
   	}
	return self;
}


- (void) LaunchLevel: (CCMenuItem*) sender
{
	// Do Something
    PackageParser* aParser = [PackageParser sharedPackageParser];
    int index = sender.tag;
    if (aParser.player) {
        [(Room*)[self.roomPool objectAtIndex:index] joinRoomWithPlayer:aParser.player];
        aParser.state = PlayerStateEnteringRoom;
    }
    aParser = nil;
}
-(void)dealloc
{
    [_roomPool release];
    _roomPool = nil;
    
    tempLabel = nil;
	[super dealloc];
}

-(void)setupMenu
{
	// Create some menu items
	CCMenuItemImage * menuItem1 = [CCMenuItemImage itemFromNormalImage:@"createButton.png"
														 selectedImage: @"createPressed.png"
																target:self
															  selector:@selector(transit:)];
	menuItem1.tag = CREATROOM;
	CCMenuItemImage * menuItem2 = [CCMenuItemImage itemFromNormalImage:@"JoinButton.png"
														 selectedImage: @"JoinPressed.png"
																target:self
															  selector:@selector(transit:)];
	menuItem2.tag = JOINROOM;
	CCMenuItemImage * menuItem3 = [CCMenuItemImage itemFromNormalImage:@"logoutButton.png"
														 selectedImage: @"LogoutPressed.png"
																target:self
															  selector:@selector(transit:)];
	menuItem3.tag = LOGOUT;
    
    CCMenuItemImage * menuItem4 = [CCMenuItemImage itemFromNormalImage:@"OptionButton.png"
														 selectedImage: @"OptionPressed.png"
																target:self
															  selector:@selector(transit:)];
	menuItem4.tag = OPTION;
    
	// Create a menu and add your menu items to it
	CCMenu * myMenu = [CCMenu menuWithItems:menuItem1, menuItem2, menuItem3, menuItem4, nil];
	
	myMenu.position = ccp(500, 100);
	// Arrange the menu items vertically
	[myMenu alignItemsHorizontally];
	
	// add the menu to your scene
	[self addChild:myMenu z:1 tag:999];
}

-(void)transit:(CCMenuItem*)sender
{
	//connect to server
    PackageParser* aParser = [PackageParser sharedPackageParser];
	if (sender.tag == CREATROOM) 
    {
        //disable other buttons
        CCMenuItemImage* item1 = (CCMenuItemImage*)[sender.parent getChildByTag:CREATROOM];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:JOINROOM];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:LOGOUT];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:OPTION];
        item1.isEnabled = NO;

        if([self getChildByTag:CREATELAYER] == nil){
        CreateRoomLayer *cr = [CreateRoomLayer node];
        
        [self addChild:cr z:1 tag:CREATELAYER];
        }
        
    }
    else if(sender.tag == JOINROOM)
    {
        //disable other buttons
        CCMenuItemImage* item1 = (CCMenuItemImage*)[sender.parent getChildByTag:CREATROOM];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:JOINROOM];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:LOGOUT];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:OPTION];
        item1.isEnabled = NO;

        if (aParser.player) {
            [(Room*)[self.roomPool objectAtIndex:0] joinRoomWithPlayer:aParser.player];
            aParser.state = PlayerStateEnteringRoom;
        }
        
    }
    else if(sender.tag == LOGOUT){
        //disable other buttons
        CCMenuItemImage* item1 = (CCMenuItemImage*)[sender.parent getChildByTag:CREATROOM];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:JOINROOM];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:LOGOUT];
        item1.isEnabled = NO;
        item1 = (CCMenuItemImage*)[sender.parent getChildByTag:OPTION];
        item1.isEnabled = NO;
        if(aParser.player){
            aParser.state = PlayerStateLoggingOut;
        }
        

    }
    else if(sender.tag == OPTION)
    {
        if([self getChildByTag:OPTIONLAYER] == nil){
            OptionLayer *ol = [OptionLayer node];
        
            [self addChild:ol z:600 tag:OPTIONLAYER];
        }
    }

    aParser = nil;
	
}

-(void)addRoom:(Room*)aRoom
{
    [self.roomPool addObject:aRoom];
}


@end
